package servlet;

import com.google.gson.Gson;
import entity.Order;
import entity.OrderDetail;
import service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/OrderDetailsServlet")
public class OrderDetailsServlet extends HttpServlet {
    private OrderService orderService = new OrderService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json; charset=UTF-8");

        try {
            // 获取请求中的订单ID
            int orderId = Integer.parseInt(request.getParameter("orderId"));

            // 调用服务层方法获取订单详情
            List<OrderDetail> orderDetails = orderService.getOrderDetailsByOrderId(orderId);

            if (orderDetails != null && !orderDetails.isEmpty()) {
                // 转换订单详情为 JSON 格式
                StringBuilder jsonBuilder = new StringBuilder("[");
                for (int i = 0; i < orderDetails.size(); i++) {
                    OrderDetail detail = orderDetails.get(i);
                    jsonBuilder.append("{")
                            .append("\"productId\":").append(detail.getProductId()).append(",")  // Added productId
                            .append("\"name\":\"").append(detail.getProductName()).append("\",")
                            .append("\"price\":").append(detail.getPrice()).append(",")
                            .append("\"quantity\":").append(detail.getQuantity())
                            .append("}");

                    if (i < orderDetails.size() - 1) {
                        jsonBuilder.append(",");
                    }
                }
                jsonBuilder.append("]");

                // 返回 JSON 数据
                response.getWriter().write(jsonBuilder.toString());
            } else {
                // 如果订单详情为空
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("{\"status\": \"error\", \"message\": \"订单未找到\"}");
            }
        } catch (NumberFormatException e) {
            // 处理无效的订单ID
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("{\"status\": \"error\", \"message\": \"无效的订单ID\"}");
        } catch (Exception e) {
            // 处理其他异常
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("{\"status\": \"error\", \"message\": \"服务器内部错误\"}");
        }
    }

}
